/**
 * @file name HttpUtils.java
 */
package com.digital.community.common.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Set;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;

/**
 * 
 * @author yarine.gao
 * @date 2011-9-7
 * @version 1.0.0
 */
public class HttpUtils {
	public static final int NETWORK_ERROR = -1;//请求无响应,及其它异常(响应码不为200)
	public static final int NO_POWER = -2;//没有权限
	public static final int OUT_OF_TIME= -3;
	public static final int SUCCESS = 1;
	private static String ver = null;
	public static final String DEFAULT_URL = "http://192.168.1.101:8093/SZSQGLXT/";
//	public static final String DEFAULT_URL = "http://61.178.41.92:9999/SZSQGLXT/";
	public static Bundle getPost(String u, HashMap<String, String> params, int timeout, Context c) {
		
		String urlPrefix = DEFAULT_URL;
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
		String ipUserSet = sp.getString("ip", "");
		if(StringUtils.isNotBlank(ipUserSet)) {
			urlPrefix = ipUserSet;
		}
		
		String content = null;
		String mval = null;
		Bundle bundle = new Bundle();
		try {
			
			System.out.println("url: " + (urlPrefix + u));
			
			URL url = new URL(urlPrefix + u);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			conn.setUseCaches(false);
			conn.setConnectTimeout(timeout);
			
			if(params != null) {
				if(StringUtils.isBlank(ver)) {
					PackageInfo pkgInfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
					params.put("ver", pkgInfo.versionName);
				}
				
				conn.setDoOutput(true);
				StringBuffer buffer = new StringBuffer(100);
				Set<String> keySet = params.keySet();
				String encKey = null;
				for(String key : keySet) {
					//加密
					if(params.get(key) == null || "".equals(params.get(key))) {
						continue;
					}
					buffer.append("&").append(key).append("=").append(URLEncoder.encode(params.get(key), "UTF-8"));
				}
				
				DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
				dos.writeBytes(buffer.substring(1));
				dos.flush();
				dos.close();
			}
			
			conn.connect();
			if(conn.getResponseCode() != 200) {
				bundle.putInt("code", NETWORK_ERROR);
				return bundle;
			}
			
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			StringBuffer buffer = new StringBuffer();
			String line = null;
			while((line = br.readLine()) != null) {
				buffer.append(line);
			}
			content = URLDecoder.decode(buffer.toString(), "utf-8");
			
			mval = conn.getHeaderField("MVAL");
			conn.disconnect();
		} catch (Exception e) {
			System.out.println("HttpUtils:" + e);//TODO 测试用,发布时删除
			bundle.putInt("code", NETWORK_ERROR);
			return bundle;
		}
		if("<NO POWER>".equals(mval)) {
			bundle.putInt("code", NO_POWER);
		} else if("<OUT OF TIME>".equals(mval)) {
			bundle.putInt("code", OUT_OF_TIME);
		} else {
			bundle.putInt("code", SUCCESS);
			bundle.putString("content", content);
		}
		
		return bundle;
	}

	public static HashMap<String, Object> getInputStream(String u, HashMap<String, String> params) {
		InputStream is = null;
		int len = 0;
		try {
			//服务端需要记录下所有的访问记录,有些应用是未加密的,无法判断是否加密,所以前面加上了前缀
			StringBuffer buffer = new StringBuffer(DEFAULT_URL);
			buffer.append(u);
			
			
			if(params != null) {
				
				Set<String> keySet = params.keySet();
				String encKey = null;
				for(String key : keySet) {
					//加密
					if(params.get(key) == null || "".equals(params.get(key))) {
						continue;
					}
					buffer.append("&").append(key).append("=").append(URLEncoder.encode(params.get(key), "UTF-8"));
				}
			}
			
			URL url = new URL(buffer.toString());
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn = (HttpURLConnection)url.openConnection();
			len = conn.getContentLength();
			is = conn.getInputStream();
		} catch (Exception e) {
			System.out.println(e);
		}
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("is", is);
		map.put("len", len);
		return map;
	}
	
//	public static int downloadFile(String u, HashMap<String, String> params, String path, String fileName) {
//
//		InputStream is = null;
//		try {
//			//服务端需要记录下所有的访问记录,有些应用是未加密的,无法判断是否加密,所以前面加上了前缀
//			String encAction = CodeUtils.encode(u);
//			System.out.println(getURL() + encAction);
//			URL url = new URL(getURL() + encAction);
//			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//			conn.setDoInput(true);
//			conn.setRequestMethod("POST");
//			conn.setUseCaches(false);
//			if(params != null) {
//				conn.setDoOutput(true);
//				StringBuffer buffer = new StringBuffer(100);
//				Set<String> keySet = params.keySet();
//				String encKey = null;
//				for(String key : keySet) {
//					if("uid".equalsIgnoreCase(key)) {
//						encKey = params.get(key);
//					} else {
//						//加密
//						if(params.get(key) == null || "".equals(params.get(key))) {
//							continue;
//						}
//						encKey = CodeUtils.encode(params.get(key));
//					}
//					buffer.append("&").append(key).append("=").append(URLEncoder.encode(encKey, "UTF-8"));
//				}
//				buffer.append("&ver").append("=").append(URLEncoder.encode(CommonBean.ver, "UTF-8"));
//				buffer.append("&isEncode=1");
//				DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
//				System.out.println(buffer.substring(1));
//				dos.writeBytes(buffer.substring(1));
//				dos.flush();
//				dos.close();
//			}
//			conn = (HttpURLConnection)url.openConnection();
//			is = conn.getInputStream();
//		} catch (Exception e) {
//			System.out.println(e);
//		}
//		
//		return is;
//	}
	
	private static boolean isFileExist(String path, String fileName) {
		File file = new File(path + fileName);
		return file.exists();
	}
	private static void deleteFile(String path, String fileName) {
		File file = new File(path + fileName);
		if (file.exists())
			file.delete();
	}
	public File createFile(String path, String fileName) throws IOException {
		File file = new File(path + fileName);
		file.createNewFile();
		return file;
	}
	
	private static void closeOutputStream(OutputStream os) {
		if(os != null) {
			try {
				os.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	private static void closeInputStream(InputStream is) {
		if(is != null) {
			try {
				is.close();
			} catch (IOException e1) {
				
			}
		}
	}
	
	private static void toCreateDirIfNotExitst(String path) {
		File f = new File(path);
		if(!f.exists()) {
			f.mkdirs();
		}
	}
}